package com.ynunicom.dc.dingdingcontractapp.configuration.schedule.skipschedule;

import com.ynunicom.dc.dingdingcontractapp.entity.ContractEntity;
import com.ynunicom.dc.dingdingcontractapp.utils.TimeStamp13To10;
import lombok.extern.slf4j.Slf4j;
import org.flowable.engine.TaskService;
import org.flowable.task.api.Task;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Conditional;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.Map;

/**
 * @author: jinye.Bai
 * @date: 2020/6/9 10:35
 */
@Component
@Conditional(ContractSkipScheduleCondition.class)
@Slf4j
public class ContractSkipSchedule {

    @Autowired
    TaskService taskService;

    @Scheduled(fixedDelay = 24*3600*1000)
    public void skip(){
        List<Task> taskList = taskService.createTaskQuery().taskDefinitionKey("runningContract").list();
        for (Task task:
             taskList) {
            ContractEntity contractEntity = (ContractEntity) taskService.getVariables(task.getId()).get("contract");
            long endDate = contractEntity.getEndDate();
            long nowDate = TimeStamp13To10.trans(System.currentTimeMillis());
            if (nowDate-endDate>=0){
                Map<String,Object> map = taskService.getVariables(task.getId());
                map.put("endMethod","endByTime");
                log.info("发起人为:[{}]的合同[{}]，文件名[{}]合同期满结束",map.get("applyUserId"),contractEntity.getName(),contractEntity.getPath());
                taskService.addComment(task.getId(),task.getProcessInstanceId(),"endMethod","timeOut");
                taskService.complete(task.getId(),map);
            }
        }
    }
}
